package com.example.demothreadlocal.service.impl;

import com.example.demodao.entity.SysUser;
import com.example.demodao.mapper.SysUserMapper;
import com.example.demothreadlocal.service.AsyncService;
import com.example.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhang
 */
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {
    /*@Override
    @Async("asyncServiceExecutor")
    public void executeAsync(List<SysUser> list, SysUserService sysUserService, CountDownLatch countDownLatch) {
        try {
            log.warn("start executeAsync");
            //异步线程要做的事情
            addLogOutputResultBatch();
            log.warn("end executeAsync");
        } finally {
            countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
        }
    }

    @Override
    public int addLogOutputResultBatch() {
        // 模拟数据
        List<SysUser> listUser = getTestData();
        //测试每100条数据插入开一个线程
        // List<List<SysUser>> lists = ConvertHandler.splitList(logOutputResults, 100);
        // List<SysUser> lists = ConvertHandler.splitList(listUser, 100);
        ///两千条数据开一条线程
        int batchSize = 2000;
        int number =listUser.size() % batchSize == 0 ? listUser.size() / batchSize :listUser.size() / batchSize+1;
        CountDownLatch countDownLatch = new CountDownLatch(number);
        for (SysUser listSub:listUser) {
            executeAsync(listSub, sysUserService,countDownLatch);
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            log.error("阻塞异常:"+e.getMessage());
        }
        return listUser.size();
    }
*/
    private List<SysUser> getTestData(){
        List<SysUser> list=new ArrayList<>();

        return list;
    }

    /**
     * 执行异步任务 * 可以根据需求，自己加参数拟定，我这里就做个测试演示
     *
     * @param countDownLatch
     * @param catalogList
     */
    @Override
    @Async("asyncServiceExecutor")
    public void asyncBatchInsertCatalog(CountDownLatch countDownLatch, List<SysUser> catalogList) {
        try{
            log.warn("start Batch Insert");
            //异步线程要做的事情
            // addLogOutputResultBatch();
            //每个线程要做的操作
            log.warn("end Batch Insert");
        }finally {
            // 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            countDownLatch.countDown();
        }
    }
}